package com.gxd.commons.utils;


import com.gxd.commons.annotation.FieldAnnotation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.regex.Matcher;

import static java.util.regex.Pattern.compile;

public class StringUtils extends org.apache.commons.lang3.StringUtils {
    private static final Logger log = LoggerFactory.getLogger(StringUtils.class);

    public static String formatDuring(long ms) {
        int ss = 1000;
        int mi = ss * 60;
        int hh = mi * 60;
        int dd = hh * 24;

        long day = ms / dd;
        long hour = (ms - day * dd) / hh;
        long minute = (ms - day * dd - hour * hh) / mi;
        long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;
        //天
        String strDay = day < 10 ? "0" + day : "" + day;
        //小时
        String strHour = hour < 10 ? "0" + hour : "" + hour;
        //分钟
        String strMinute = minute < 10 ? "0" + minute : "" + minute;
        //秒
        String strSecond = second < 10 ? "0" + second : "" + second;
        //毫秒
        String strMilliSecond = milliSecond < 10 ? "0" + milliSecond : "" + milliSecond;
        strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond : "" + strMilliSecond;

        return strDay + " days " + strHour + " hours " + strMinute + " minutes "
                + strSecond + " seconds "+ strMilliSecond + " milliSecond ";
    }

    public static int getStringLength(String str, String encoding) {
        if(isEmpty(str)) {
            return 0;
        } else {
            try {
                return str.getBytes(encoding).length;
            } catch (UnsupportedEncodingException e) {
                log.error("异常："+e.getMessage());
                return 0;
            }
        }
    }


    /**
     * 通过对象获取注解以及值
     * @param object
     * @return
     */
    public static String getOldValue(Object object){
        StringBuffer sb = new StringBuffer();
        Field[] fields = object.getClass().getSuperclass().getDeclaredFields();
        Object value = "";
        try {
            for (Field field : fields) {
                boolean fieldHasAnno = field.isAnnotationPresent(FieldAnnotation.class);
                if (fieldHasAnno) {
                    FieldAnnotation fieldAnno = field.getAnnotation(FieldAnnotation.class);
                    String getMethodName = ListUtils.getMethodByFieldName(object.getClass(),field.getName()); //转换成字段的get方法
                    Method getMethod = object.getClass().getSuperclass().getMethod(getMethodName, new Class[]{});
                    //这个对象字段get方法的值
                    value = getMethod.invoke(object, new Object[]{});
                    //输出注解属性
                    String desc = fieldAnno.desc();
                    sb.append(desc + ":" + value + "\r\n");
                }
            }
        } catch (Exception e) {
            log.error("异常信息："+e.getMessage());
        }
        return sb.toString();

    }

    /**
     * 创建指定数量的随机字符串
     *
     * @param isNumber 是否是数字
     * @param length
     * @return
     */
    public static String randomStr(boolean isNumber, int length) {
        String retStr = "";
        String strTable = isNumber ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);

        return retStr;
    }


    /**
     * 获取第三次出“/”的位置（http://127.0.0.1:8080/test）
     * @param str
     * @return
     */
    public static int getCharacterPosition(String str){
        //这里是获取"/"符号的位置
        Matcher slashMatcher = compile("/").matcher(str);
        int mIdx = 0;
        while(slashMatcher.find()) {
            mIdx++;
            //当"/"符号第三次出现的位置
            if(mIdx == 3){
                break;
            }
        }
        if(mIdx != 3){
            return str.length();
        }
        return slashMatcher.start();
    }

    /**
     * 获取第n次出str的位置（http://127.0.0.1:8080/test）
     * @param str
     * @param index
     * @return
     */
    public static int getCharacterPosition(String str,int index){
        //这里是获取"/"符号的位置
        Matcher slashMatcher = compile("/").matcher(str);
        int mIdx = 0;
        while(slashMatcher.find()) {
            mIdx++;
            //当"/"符号第三次出现的位置
            if(mIdx == index){
                break;
            }
        }
        if(mIdx != index){
            return str.length();
        }
        return slashMatcher.start();
    }

    /**
     * 获取第n次出str的位置（http://127.0.0.1:8080/test）
     * @param str
     * @param separator
     * @param index
     * @return
     */
    public static int getCharacterPosition(String str,String separator,int index){
        //这里是获取"/"符号的位置
        Matcher slashMatcher = compile(separator).matcher(str);
        int mIdx = 0;
        while(slashMatcher.find()) {
            mIdx++;
            //当"/"符号第三次出现的位置
            if(mIdx == index){
                break;
            }
        }
        if(mIdx != index){
            return str.length();
        }
        return slashMatcher.start();
    }

    public static boolean isEmpty(String[] values) {
        if (values == null || values.length == 0) {
            return true;
        }
        for (String value : values) {
            if (!isEmpty(value)) {
                return false;
            }
        }
        return true;
    }
    public static void main(String[] args) {
        long stat = System.currentTimeMillis();

        System.out.println(formatDuring(System.currentTimeMillis()+100340654L-stat));
        System.out.println(randomStr(true,6));
    }
}
